import Polygon from "ol/geom/Polygon";
import MultiPolygon from "ol/geom/MultiPolygon";
import { Feature } from "ol";
import { MultiPoint } from "ol/geom";
export class MapManager {
  mapEventFunArray = [];
  mapMouseEvent = {};
  constructor(map) {
    this.currentMap = map;
    this.mapView = map.getView(); //视图容器
    this.initMapHtmlEle();
    this.initMouseEvent();
    this.changeMapCursor("default");
    // this.layers = map.getAllLayers(); //图层容器
    // this.layerManager = new LayerManager(map)
    // this.overlayManager=new OverlayManager(map)
    // this.mapManager=new MapManager(map)
  }
  // 获取初始化地图元素
  initMapHtmlEle() {
    let mapTarget = this.currentMap.getTargetElement();
    if (mapTarget) {
      this.mapTargetEle = mapTarget;
    }
  }
  // 初始化地图鼠标事件
  initMouseEvent() {
    let mousedownUrl = "grabbing";
    let mouseupUrl = "grab";
    this.mapTargetEle.style.cursor = mouseupUrl;
    this.mapMouseEvent["moveHandler"] = (event) => {
      this.mapTargetEle.style.cursor = mousedownUrl;
    };

    this.mapMouseEvent["mouseupHandler"] = (event) => {
      this.mapTargetEle.style.cursor = mouseupUrl;
      this.mapTargetEle.removeEventListener(
        "mousemove",
        this.mapMouseEvent["moveHandler"],
        false
      );
    };
    this.mapMouseEvent["mousedownHandler"] = (event) => {
      this.mapTargetEle.style.cursor = mousedownUrl;
      this.mapTargetEle.addEventListener(
        "mousemove",
        this.mapMouseEvent["moveHandler"],
        false
      );
    };
  }

  //改变地图鼠标手势
  changeMapCursor(type) {
    // const mouseupCur = require('../../assets/images/openhand.cur')
    // let mouseupUrl = `url("${mouseupCur}") 8 8, default`
    let mouseupUrl = "grab";
    this.mapTargetEle.style.cursor = mouseupUrl;
    if (type === "default") {
      this.mapTargetEle.addEventListener(
        "mousedown",
        this.mapMouseEvent["mousedownHandler"],
        false
      );
      this.mapTargetEle.addEventListener(
        "mouseup",
        this.mapMouseEvent["mouseupHandler"],
        false
      );
    } else if (type === "draw" || type === "edit") {
      this.mapTargetEle.style.cursor = "default";
      this.mapTargetEle.removeEventListener(
        "mousemove",
        this.mapMouseEvent["moveHandler"],
        false
      );
      this.mapTargetEle.removeEventListener(
        "mousedown",
        this.mapMouseEvent["mousedownHandler"],
        false
      );
      this.mapTargetEle.removeEventListener(
        "mouseup",
        this.mapMouseEvent["mouseupHandler"],
        false
      );
    } else if (type === "select") {
      this.mapTargetEle.style.cursor = "pointer";
      this.mapTargetEle.removeEventListener(
        "mousemove",
        this.mapMouseEvent["moveHandler"],
        false
      );
      this.mapTargetEle.removeEventListener(
        "mousedown",
        this.mapMouseEvent["mousedownHandler"],
        false
      );
      this.mapTargetEle.removeEventListener(
        "mouseup",
        this.mapMouseEvent["mouseupHandler"],
        false
      );
    }
  }

  onMapEvent(type, callback) {
    this.mapEvenFun(type, callback, this.currentMap);
    if (this.mapEventFunArray.length > 0) {
      let len = this.mapEventFunArray.length;
      for (let i = 0; i < len; i++) {
        if (this.mapEventFunArray[i].callback == callback) {
          this.currentMap.on(type, this.mapEventFunArray[i].func);
        }
      }
    }
  }

  /**
   * 事件
   * @param {*} type
   * @param {*} callback
   * @param {*} map
   */
  mapEvenFun(type, callback, map) {
    this.mapEventFunArray
      ? this.mapEventFunArray
      : (this.mapEventFunArray = []);
    const that = this;
    let eventFun = function (event) {
      event["position"] = event.coordinate;
      const pixel = event.pixel;
      const dataArr = [];
      // if (event.type === 'singleclick') {
      //
      if (event.type === "singleclick" || event.type === "pointermove") {
        // console.log('mapmanager')
        let featureArray = [];
        let pointFeatureArray = [];
        let polygonFeatureArray = [];
        let regionFeature = undefined;
        map.forEachFeatureAtPixel(pixel, (feature, layer) => {
          // console.log(feature)
          if (feature) {
            featureArray.push(feature);
            //捕捉到要素
            if (feature.getProperties().features) {
              //聚合情况下
              if (feature.getProperties().features.length == 1) {
                //只有一个要素
                feature = feature.getProperties().features[0]; //获取该要素
                pointFeatureArray.push(feature);
                // 聚合->单个要素
              } else {
                // 聚合->多个要素
                // clusterFlag = true
                pointFeatureArray = pointFeatureArray.concat(
                  feature.getProperties().features
                );
              }
            } else {
              //非聚合情况下
              // console.log(feature.getProperties())
              if (feature.getProperties()["levelid"]) {
                regionFeature = feature;
              }
              let featureData = feature.getProperties();
              if (!featureData) return;
              // let featureType =
              //   featureData["type"] ||
              //   (featureData.data && featureData.data["type"]);
              // if (!featureType) return;
              if (
                feature.getGeometry() instanceof Polygon ||
                feature.getGeometry() instanceof MultiPolygon
              ) {
                polygonFeatureArray.push(feature);
              } else {
                pointFeatureArray.push(feature);
              }
            }
          }
        });
        featureArray = pointFeatureArray.length
          ? pointFeatureArray
          : polygonFeatureArray.length
          ? polygonFeatureArray
          : [];
        if (event.type === "singleclick") {
          console.log(featureArray)
          if(featureArray.length>1){
            // 默认设置层级小余15级放大地图
            if(that.currentMap.getView().getZoom() < 15){
              const f = new Feature()
              f.setProperties({
                features: featureArray,
              })
              that.selectStyleFunction(f)
              callback({
                position: event['position'],
                target: map.getTargetElement(),
              })
            }else{
              
              featureArray.forEach((featuredata) => {
                let singleFeature = featuredata
                // => 单个
                let eventData = {}
                eventData['position'] = event.coordinate
                eventData['type'] = type
                eventData['target'] = map.getTargetElement()
                eventData['feature'] = singleFeature
                eventData['data'] = singleFeature.getProperties(),
                // dataArr.push(eventData)
                console.log(eventData)
                
                callback(eventData)
                return
              })
            }

          }else if (featureArray.length === 1){
            
            // 返回单个数据
            callback({
              position: event["position"],
              data:featureArray[0].getProperties(),
              target: map.getTargetElement(),
              feature:featureArray[0],
            })
          }else if (regionFeature) {
            callback({
              regionFeature,
            })
          } else {
            callback({ event })
          }
        } else {
          callback({
            position: event["position"],
            type: type,
            feature: featureArray,
          });
        }
      } else {
        // 最初的
        map.forEachFeatureAtPixel(pixel, (features) => {
          let eventData = {};
          eventData["position"] = event.coordinate;
          eventData["type"] = type;
          eventData["target"] = map.getTargetElement();
          if (features.get("features")) {
            const length = features.get("features").length;
            eventData["features"] = features.get("features")[length - 1];
            eventData["data"] = features
              .get("features")
              [length - 1].get("data");
          } else {
            eventData["feature"] = features;
            eventData["data"] = features.get("data");
          }
          dataArr.push(eventData);
        });
        if (dataArr.length > 0) {
          callback(dataArr[0]);
        } else {
          callback({
            position: event["position"],
            type: type,
            target: map.getTargetElement(),
          });
        }
      }
    };
    this.mapEventFunArray.push({ callback: callback, func: eventFun });
  }




  //设置聚合图元选择中后处理
  selectStyleFunction(feature) {
    if (feature) {
      var originalFeatures = feature.get('features')
      if (originalFeatures.length <= 1) {
        return
      }
      var multiPoints = new MultiPoint([])
      for (var i = 0; i < originalFeatures.length; i++) {
        var point = originalFeatures[i].getGeometry()
        multiPoints.appendPoint(point)
      }

      var myView = this.currentMap.getView()
      var size = this.currentMap.getSize()
      var paddingSize = size[0] / 10
      if (size[0] > size[1]) {
        paddingSize = size[1] / 10
      }
      myView.fit(multiPoints, {
        size: this.currentMap.getSize(),
        padding: [paddingSize, paddingSize, paddingSize, paddingSize],
        duration: 1500,
      })
    }
  }


  //移除常规地图事件监听
   unMapEvent(type, callback) {
    let funIndex
    let len = this.mapEventFunArray.length
    for (let i = 0; i < len; i++) {
      if (this.mapEventFunArray[i].callback == callback) {
        this.currentMap.un(type, this.mapEventFunArray[i].func)
        funIndex = i
      }
    }
    this.mapEventFunArray.splice(funIndex, 1)
  }

}
